import 'package:flutter/material.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:get/state_manager.dart';
import 'package:short_drama/pages/mine/change.dart';
import 'package:short_drama/utils/colors.dart';
import 'package:image_picker/image_picker.dart';
import 'package:short_drama/models/user_model.dart';
import 'package:short_drama/utils/http_util.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:short_drama/pages/widgets/dialog.dart';
import 'package:short_drama/utils/float.dart';
import 'dart:io';

class UserPage extends StatefulWidget {
  const UserPage({Key? key}) : super(key: key);

  State<UserPage> createState() => _UserPageState();
}

class _UserPageState extends State<UserPage> {
  final TextEditingController _namecontroller = TextEditingController(text: '');
  final TextEditingController _gendercontroller = TextEditingController(
    text: '',
  );
  final TextEditingController _phonecontroller = TextEditingController(
    text: '',
  );
  final TextEditingController _invitecontroller = TextEditingController(
    text: '',
  );
  UserModel viewModel = UserModel(
    '',
    0,
    '',
    '',
    '',
    '',
    '',
    '',
    '',
    0,
    '',
    '',
    0,
  );
  String headUrl = '';

  @override
  void initState() {
    super.initState();
    _getUserInfoData();
  }

  _getUserInfoData() async {
    try {
      final model = await UserViewModel().fetchUserInfoData();
      setState(() {
        viewModel = model;
        headUrl = viewModel.headimg;
        _namecontroller.text = viewModel.nickname;
        _gendercontroller.text = viewModel.sex_name;
        _phonecontroller.text = viewModel.mobile;
      });
    } catch (e) {
      print('获取数据失败_getServiceData');
    }
  }

  File? _image;
  Future<void> _takePhoto() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      setState(() {
        _image = File(pickedFile.path);
        _updateHead(_image!);
      });
    } else {
      print('用户取消拍照');
    }
  }

  _updateHead(File file) async {
    if (file != null) {
      final result = await UserViewModel().uploadFile(_image!);
      UserViewModel().updateUserHeadImage(result ?? '');
      headUrl = result;
    }
  }

  _doneAction() async {
    var name = _namecontroller.text;
    if (name.length > 0 && (name != viewModel.nickname)) {
      UserViewModel().updateUserName(name);
    }

    var gender = _gendercontroller.text;
    if (gender.length > 0 && (gender != viewModel.sex_name)) {
      UserViewModel().updateUsergender((gender == '男') ? '1' : '2');
    }

    var invite = _invitecontroller.text;
    if (invite.length > 0) {
      UserViewModel().updateInvite(invite);
    }
  }

  @override
  Widget build(BuildContext context) {
    final args = Get.arguments as Map<String, dynamic>;
    String invite = '${args['invite'] ?? ''}';
    return Scaffold(
      backgroundColor: ClientColors.ff0a0f12,
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.white),
        leading: IconButton(
          onPressed: () => Get.back(result: {'headUrl': headUrl}),
          icon: Icon(Icons.arrow_back_ios),
        ),
        backgroundColor: ClientColors.odffffff,
        centerTitle: false,
        titleSpacing: FloatConstance.navBarSpace,
        title: Text(
          '个人信息',
          style: TextStyle(color: Colors.white, fontSize: 18),
        ),
        actions: [
          GestureDetector(
            onTap: () {
              _doneAction();
            },
            child: Container(
              margin: EdgeInsets.only(right: 10),
              child: Text(
                '完成',
                style: TextStyle(fontSize: 14, color: ClientColors.ff4abc9c),
              ),
            ),
          ),
        ],
      ),
      body: Container(
        margin: EdgeInsets.only(top: 32),
        child: Column(
          children: [
            // 头像
            GestureDetector(
              onTap: () {
                _takePhoto();
              },
              child: Container(
                margin: EdgeInsets.only(bottom: 32),
                child:
                    _image == null
                        ? (viewModel.headimg.length > 0)
                            ? Container(
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(51),
                                color: Colors.red,
                              ),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(51),
                                child: Image.network(
                                  headUrl,
                                  fit: BoxFit.cover,
                                  width: 102,
                                  height: 102,
                                ),
                              ),
                            )
                            : Stack(
                              alignment: Alignment.center,
                              children: [
                                Container(
                                  alignment: Alignment.center,
                                  child: Image.asset(
                                    'assets/images/icon_edit_head.png',
                                    width: 102,
                                    height: 102,
                                  ),
                                ),
                                SizedBox(
                                  width: 32,
                                  height: 26,
                                  child: Image.asset(
                                    'assets/images/icon_carema.png',
                                  ),
                                ),
                                Container(
                                  margin: EdgeInsets.only(top: 50),
                                  child: Text(
                                    '更换头像',
                                    style: TextStyle(
                                      fontSize: 13,
                                      color: ClientColors.boffffff,
                                    ),
                                  ),
                                ),
                              ],
                            )
                        : Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(51),
                            color: Colors.red,
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(51),
                            child: Image.file(
                              _image!,
                              fit: BoxFit.cover,
                              width: 102,
                              height: 102,
                            ),
                          ),
                        ),
              ),
            ),
            // 昵称
            Container(
              margin: EdgeInsets.only(left: 16, right: 16),
              padding: EdgeInsets.only(left: 16, right: 16),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                color: ClientColors.odffffff,
              ),
              height: 60,
              child: Row(
                children: [
                  Text(
                    '昵称',
                    style: TextStyle(
                      fontSize: 15,
                      color: ClientColors.aaffffff,
                    ),
                  ),
                  Expanded(child: Container()),
                  Expanded(
                    flex: 1,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10),
                      child: TextField(
                        decoration: InputDecoration(border: InputBorder.none),
                        textAlign: TextAlign.right,
                        style: TextStyle(color: Colors.white),
                        controller: _namecontroller,
                        onSubmitted: (value) => onTap(value.trim()),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            //性别
            Container(
              margin: EdgeInsets.only(left: 16, top: 10, bottom: 10, right: 16),
              padding: EdgeInsets.only(left: 16, right: 16),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                color: ClientColors.odffffff,
              ),
              height: 60,
              child: Row(
                children: [
                  Text(
                    '性别',
                    style: TextStyle(
                      fontSize: 15,
                      color: ClientColors.aaffffff,
                    ),
                  ),
                  Expanded(child: Container()),
                  SizedBox(
                    width: 100,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10),
                      child: TextField(
                        enabled: false,
                        decoration: InputDecoration(border: InputBorder.none),
                        textAlign: TextAlign.right,
                        style: TextStyle(color: Colors.white),
                        controller: _gendercontroller,
                        onSubmitted: (value) => onTap(value.trim()),
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: () async {
                      _showBottomSheet(context);
                    },
                    child: SizedBox(
                      height: 30,
                      width: 30,
                      child: Image.asset(
                        'assets/images/icon_user_arrow.png',
                        width: 6,
                        height: 12,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            // 手机
            Container(
              margin: EdgeInsets.only(left: 16, right: 16, bottom: 10),
              padding: EdgeInsets.only(left: 16, right: 16),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                color: ClientColors.odffffff,
              ),
              height: 60,
              child: Row(
                children: [
                  Text(
                    '手机',
                    style: TextStyle(
                      fontSize: 15,
                      color: ClientColors.aaffffff,
                    ),
                  ),
                  Expanded(child: Container()),
                  SizedBox(
                    width: 140,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10),
                      child: TextField(
                        enabled: false,
                        decoration: InputDecoration(border: InputBorder.none),
                        textAlign: TextAlign.right,
                        style: TextStyle(color: Colors.white),
                        controller: _phonecontroller,
                        onSubmitted: (value) => onTap(value.trim()),
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      Get.to(
                        () => ChangePage(),
                        arguments: {'phone': viewModel.mobile},
                      );
                    },
                    child: SizedBox(
                      height: 30,
                      width: 30,
                      child: Image.asset(
                        'assets/images/icon_user_arrow.png',
                        width: 6,
                        height: 12,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(left: 16, right: 16),
              padding: EdgeInsets.only(left: 16, right: 16),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                color: ClientColors.odffffff,
              ),
              height: (invite.length > 0) ? 60 : 0,
              child: Row(
                children: [
                  Text(
                    '绑定上级',
                    style: TextStyle(
                      fontSize: 15,
                      color: ClientColors.aaffffff,
                    ),
                  ),
                  Expanded(child: Container()),
                  SizedBox(
                    width: 140,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10),
                      child: TextField(
                        decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: '邀请码',
                        ),
                        textAlign: TextAlign.right,
                        style: TextStyle(color: Colors.white),
                        controller: _invitecontroller,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showBottomSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: ClientColors.oxfFFFFFFF,
      builder:
          (context) => Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                title: const Text(
                  '男',
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.white),
                ),
                onTap: () {
                  Navigator.pop(context, '男');
                },
              ),
              ListTile(
                title: const Text(
                  '女',
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.white),
                ),
                onTap: () {
                  Navigator.pop(context, '女');
                },
              ),
              SizedBox(height: 20),
            ],
          ),
    ).then((value) {
      if (value.length > 0) {
        _gendercontroller.text = value ?? '';
      }
    });
  }

  onTap(String? host) async {}
}

class UserViewModel {
  Future<UserModel> fetchUserInfoData() async {
    try {
      final response = await HttpUtil().get('member/member');
      final dynamic responseData = response.data['data'];
      print(responseData);
      if (responseData == null) {
        throw Exception('Image URL not found in response');
      } else {
        return UserModel.fromJson(responseData);
      }
    } catch (e) {
      print('获取分页数据异常: $e');
      throw '';
    }
  }

  Future<String> uploadFile(File file) async {
    EasyLoading.show(status: 'loading', maskType: EasyLoadingMaskType.clear);
    try {
      final result = await HttpUtil().upload(
        'file/image',
        filePath: file.path,
        file: file,
        fileName: "身份证图片",
      );
      final dynamic responseData = result.data['data'];
      return responseData['url'] ?? '';
    } catch (e) {
      EasyLoading.showToast('请求失败');
      return '';
    }
  }

  Future<void> updateUserHeadImage(String value) async {
    try {
      final response = await HttpUtil().put(
        'member/modify/headimg',
        params: {'field': "headimg", 'value': value},
      );
      final dynamic msg = response.data['msg'] ?? '提示';
      EasyLoading.showToast(msg);
    } catch (e) {
      throw '';
    }
  }

  Future<void> updateUserName(String name) async {
    try {
      final response = await HttpUtil().put(
        'member/modify/nickname',
        params: {'field': "nickname", 'value': name},
      );
      final dynamic msg = response.data['msg'] ?? '提示';
      EasyLoading.showToast(msg);
    } catch (e) {
      throw '';
    }
  }

  Future<void> updateUsergender(String gender) async {
    try {
      final response = await HttpUtil().put(
        'member/modify/sex',
        params: {'field': "sex", 'value': gender},
      );

      final dynamic responseData = response.data['data'];
      final dynamic msg = response.data['msg'] ?? '提示';
      EasyLoading.showToast(msg);
    } catch (e) {
      throw '';
    }
  }

  Future<void> updateInvite(String invite) async {
    try {
      final response = await HttpUtil().post(
        'member/bind_member',
        params: {'member_no': invite},
      );
      final dynamic responseData = response.data['data'];
      final dynamic msg = response.data['msg'] ?? '提示';
      EasyLoading.showToast(msg);
    } catch (e) {
      throw '';
    }
  }
}
